package com.googlecode.rotools.grf;

import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class ItemDescParser extends TextParser<ItemDesc>{
	@Override
	protected String[][] splitCells(String text) {
		String[][] cells = null;
		String[] rows = splitRows(text);
		if(rows != null){
			cells = new String[rows.length][];
			
			for (int i = 0; i < rows.length; i++) {
				int n = rows[i].indexOf('#');
				int n1 = rows[i].indexOf('＃');
				if(n1 != -1 && n > n1){
					n = n1;
				}
				cells[i] = new String[2];
				cells[i][0] = rows[i].substring(0, n);
				cells[i][1] = rows[i].substring(n + 1).trim();
				if(cells[i][1].endsWith("#")){
					cells[i][1] = cells[i][1].substring(0, cells[i][1].length()-1);	
				}
			}
		}
		return cells;
	}
	protected String[] splitRows(String text) {
		ArrayList<String> list = new ArrayList<String>();
//		Pattern pattern = Pattern.compile("^\\d{1,8}#", Pattern.MULTILINE);
		Pattern pattern = Pattern.compile("^\\d{1,8}[＃#]", Pattern.MULTILINE);
		Matcher matcher = pattern.matcher(text);
		
		int start = 0, end = 0;
		while(matcher.find()){
			end = matcher.start();
			if(end != 0){
				list.add(text.substring(start, end));
				start = end;
			}
		}
		if(start != 0){
			list.add(text.substring(start));
		}
		String[] rows = null;
		if(list.size() > 0){
			rows = list.toArray(new String[list.size()]);
		}
		return rows;
		
	}
	@Override
	ItemDesc parse(String[] texts) throws IOException 
	{
		ItemDesc item = new ItemDesc();
		item.setId(texts[0]);
		item.setDescription(texts[1]);
		return item;
	}
}
